package com.hl.apple.myapplication;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.hl.apple.myapplication.Socketmanager.SocketManager;
import com.hl.apple.myapplication.Socketmanager.socketMessageInfo;
import com.hl.apple.myapplication.utils.BitmapUtil;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class ResultActivity extends AppCompatActivity implements Runnable {
    private static String TAG = ResultActivity.class.getSimpleName();
    private DatagramSocket receiveSocket, sendSocket;
    DatagramSocket socket = null;
    private byte[] receiveInfo;     //接收报文信息
    private String receiveStr = "";
    private String mHostIP = "";
    public int connectHeartTime = 0;
    public ImageView mIVWifi;
    public String mServiceIP = "";
    boolean isUploadCompleted = false;
    private SocketManager socketManager;
    private ServerSocket server;
    public int mServicePort = 13001;
    public List<socketMessageInfo> listSocketMessageInfo = new ArrayList<socketMessageInfo>();


    private ImageView ucropImage;
    private ImageView mUpload, mBack;

    public static void startWithUri(@NonNull Context context, @NonNull Uri uri) {
        Intent intent = new Intent(context, ResultActivity.class);
        intent.setData(uri);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        mHostIP = getHostIP();


        Log.e("HOST", "-------" + mHostIP);
        if (mHostIP != null) {
            String _mBrocastIP = mHostIP.substring(0, mHostIP.lastIndexOf(".")) + ".1";
            listSocketMessageInfo.add(new socketMessageInfo(_mBrocastIP, 12000, "clientStart|" + mHostIP));
            listSocketMessageInfo.add(new socketMessageInfo(_mBrocastIP, 12000, "clientStart|" + mHostIP));
            listSocketMessageInfo.add(new socketMessageInfo(_mBrocastIP, 12000, "clientStart|" + mHostIP));
        } else {
            Toast.makeText(this, "您当前未联网,为获取到IP", Toast.LENGTH_LONG).show();
            return;
        }


        try {
            server = new ServerSocket(9999);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (server != null) {
            socketManager = new SocketManager(server);
        }
        initView();

    }

    private void initView() {
        ucropImage = (ImageView) findViewById(R.id.ucropImage);
        mIVWifi = (ImageView) findViewById(R.id.ivWifi);
        mUpload = findViewById(R.id.upload);
        mBack = findViewById(R.id.back);

        String imagePath = getIntent().getData().getPath();
        Bitmap bitmap = BitmapUtil.decodeBitmap(imagePath);
        ucropImage.setImageBitmap(bitmap);

        // showStr("开始接收线程", 1);
        new UdpReceiveThread().start();
        //  showStr("开始发送线程", 1);
        new Thread(ResultActivity.this).start();
        new Thread(new ThreadShow()).start();

        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mServiceIP.length() < 7) {
                    Toast.makeText(ResultActivity.this, "未连接到服务器", Toast.LENGTH_LONG).show();
                    return;
                }

                Log.e("上传的目录", "0000:" + getIntent().getData().getPath());
                final String _picturePath = getIntent().getData().getPath();

                final String _fileName = _picturePath.trim().substring(
                        _picturePath.lastIndexOf("/") + 1);
                Toast.makeText(ResultActivity.this, "开始上传", Toast.LENGTH_LONG).show();

                Thread sendThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String response = socketManager.SendFile(_fileName, _picturePath, mServiceIP, mServicePort);
                        if (response.contains("成功")) {
                            uiHandler.sendEmptyMessage(3);
                        } else {
                            uiHandler.sendEmptyMessage(4);
                        }

                    }
                });
                sendThread.start();
            }
        });
    }


    public Handler uiHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    // showStr(mImgPath, 1);
                    break;
                case 1:
                    mIVWifi.setAlpha(1.0f);
                    connectHeartTime = 10;
                    break;

                case 3:
                    Toast.makeText(ResultActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    isUploadCompleted = true;
                    break;
                case 4:
                    //showStr("发送失败", 1);
                    isUploadCompleted = true;
                    break;
                case 10:
                    //  showStr(receiveStr, 1);
                    break;
                case 19:
                    if (connectHeartTime == 0) {
                        mIVWifi.setAlpha(0.2f);
                    } else if (connectHeartTime > 0) {
                        connectHeartTime--;
                    }
                    break;

                default:
                    break;
            }
            return false;
        }
    });


    // 线程类
    class ThreadShow implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                try {
                    Thread.sleep(1000);
                    uiHandler.sendEmptyMessage(19);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    // UDP数据接收线程
    public class UdpReceiveThread extends Thread {
        @Override
        public void run() {
            try {
                receiveSocket = new DatagramSocket(8080);
                while (true) {
                    byte[] inBuf = new byte[1024];
                    DatagramPacket inPacket = new DatagramPacket(inBuf, inBuf.length);
                    receiveSocket.receive(inPacket);
                    receiveInfo = inPacket.getData();
                    receiveStr = new String(receiveInfo, "UTF-8").trim();
                    uiHandler.sendEmptyMessage(10);
                    if (receiveStr.contains("|")) {
                        String[] _aa = receiveStr.split("\\|");
                        String _str0 = _aa[0];
                        String _str1 = _aa[1];
                        if (_str0.equals("serverStart")) {
                            if (_str1.substring(0, _str1.lastIndexOf(".")).equals(mHostIP.substring(0, mHostIP.lastIndexOf(".")))) {
                                mServiceIP = _str1;

                                listSocketMessageInfo.add(new socketMessageInfo(mServiceIP, 12000, "client|" + mHostIP));
                                listSocketMessageInfo.add(new socketMessageInfo(mServiceIP, 12000, "client|" + mHostIP));
                                listSocketMessageInfo.add(new socketMessageInfo(mServiceIP, 12000, "client|" + mHostIP));
                                uiHandler.sendEmptyMessage(1);

                            }
                        } else if (_str0.equals("server")) {
                            if (_str1.substring(0, _str1.lastIndexOf(".")).equals(mHostIP.substring(0, mHostIP.lastIndexOf(".")))) {
                                mServiceIP = _str1;

                                uiHandler.sendEmptyMessage(1);
                            }
                        } else if (_str0.equals("heartBeat")) {
                            if (_str1.substring(0, _str1.lastIndexOf(".")).equals(mHostIP.substring(0, mHostIP.lastIndexOf(".")))) {
                                mServiceIP = _str1;

                                listSocketMessageInfo.add(new socketMessageInfo(mServiceIP, 12000, "heartBeat|" + mHostIP));
                                uiHandler.sendEmptyMessage(1);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public void run() {
        while (true) {
            if (!listSocketMessageInfo.isEmpty()) {
                try {
                    socketMessageInfo smi = listSocketMessageInfo.get(0);
                    InetAddress serverAddress = InetAddress.getByName(smi.ip);
                    byte data[] = smi.info.getBytes();
                    DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress, smi.port);
                    socket.send(packet);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                listSocketMessageInfo.remove(0);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /****
     * 获取客户端IP
     * @return
     */
    public static String getHostIP() {

        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return hostIp;

    }
}
